package cn.my;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * Github文件上传工具类
 *
 * @author Sun.Q
 * @since 九月, 30 2021
 */
public class GitHub {

    private static  Result RESULT;

    public static final String ACCESS_TOKEN = "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";

    private static final Logger LOGGER = LoggerFactory.getLogger(GitHub.class);

    /**
     * 压缩图片并上传
     *
     * @param bufferedImage 图片流
     * @return 文件连接
     */
    public static Result upImg(BufferedImage bufferedImage) {

        File source = FileUtil.file("/tmp/temp.png");

        try {
            ImageIO.write(bufferedImage, "png", source);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.err(e.getMessage());
        }

        File target = FileUtil.file("/tmp/temp.jpg");

        ImgUtil.convert(source, target);

        return upFile(max(source, target));
    }

    public static File max(File a, File b) {
        return FileUtil.size(a) > FileUtil.size(b) ? b : a;
    }

    /**
     * 上传普通文件
     *
     * @param file 文件
     * @return 文件链接
     */
    public static Result upFile(File file) {

        String sfname=file.getName();

        String fileName = DateUtil.format(LocalDateTime.now(), "ddHHmmss")
                + (sfname.contains(".") ? "." + StrUtil.subAfter(file.getName(), ".", true) : "");

        String path = DateUtil.format(LocalDateTime.now(), "yyyyMM") + "/" + fileName;

        String url = "https://api.github.com/repos/sun-qiao/img/contents/";

        JSONObject parms = new JSONObject();

        parms.set("content", Base64.encode(file));

        parms.set("message", "add file");

        try {

            String out = HttpUtil.createRequest(Method.PUT, url + path)
                    .auth("token " + ACCESS_TOKEN)
                    .body(parms.toString())
                    .execute()
                    .body();

            LOGGER.info(out);

            JSONObject resultJSON = JSONUtil.parseObj(out);

            if (resultJSON.containsKey("messages")) return Result.err(resultJSON.get("messages").toString());

            JSONObject contentObj = resultJSON.getJSONObject("content");

            String sha = contentObj.getStr("sha");

            path = contentObj.getStr("path");

            //jsdeliver有时不稳定
            //String downloadUrl = "https://cdn.jsdelivr.net/gh/sun-qiao/img@master/" + path;
            String downloadUrl = "https://github-do.panbaidu.cn//https://raw.githubusercontent.com/sun-qiao/img/master/" + path;

            Result succ = Result.succ(downloadUrl, sha, path);
            RESULT=succ;
            return succ;

        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(e.toString());
        }
    }

    public static Result delFile() {

        String url = "https://api.github.com/repos/sun-qiao/img/contents/";

        JSONObject parms = new JSONObject();

        parms.set("sha", RESULT.getSha());

        parms.set("message", "delete last file");

        try {

            String out = HttpUtil.createRequest(Method.DELETE, url + RESULT.getPath())
                    .auth("token " + ACCESS_TOKEN)
                    .body(parms.toString())
                    .execute()
                    .body();

            LOGGER.info(out);

            JSONObject resultJSON = JSONUtil.parseObj(out);

            if (resultJSON.containsKey("messages")) return Result.err(resultJSON.get("messages").toString());

            return Result.delSucc();

        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(e.toString());
        }
    }


    public static void main(String[] args) {
        Result result = upFile(new File("C:\\Users\\xm955\\Desktop\\pg2.png"));
        System.out.println(result.toString());
    }

}
